import axios from 'axios'
import { showToast } from 'vant'

const api = axios.create({
  baseURL: 'http://8.137.113.18:8889/api',
  timeout: 5000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    // 统一错误处理
    const message = error.response?.data?.message || '服务器错误，请稍后重试'
    showToast({
      message,
      type: 'fail',
      duration: 2000
    })
    return Promise.reject(error)
  }
)

// 在正式API准备好之前，使用模拟数据
const mockData = {
  // 视频列表模拟数据
  videoList: [
    {
      id: 1,
      title: '警惕电信诈骗',
      description: '远离电信诈骗，保护财产安全',
      video_url: 'https://example.com/video1.mp4',
      cover: 'https://img01.yzcdn.cn/vant/cat.jpeg',
      views: '1.2w',
      likes: '2.3k'
    },
    {
      id: 2,
      title: '防范网络诈骗',
      description: '识别网络诈骗，守住钱袋子',
      video_url: 'https://example.com/video2.mp4',
      cover: 'https://img01.yzcdn.cn/vant/cat.jpeg',
      views: '8.9k',
      likes: '1.8k'
    }
  ],
  // 天气数据模拟
  weatherData: {
    city: '北京',
    temperature: 25,
    weather_type: '晴'
  },
  // 用户数据模拟
  userData: {
    id: 2860,
    username: '王大叔',
    role: 'farmer',
    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    phone: '13800138000',
    email: 'farmer1@example.com',
    stats: {
      pendingOrders: 2,
      onSaleProducts: 8
    },
    orders: {
      pending: 3,
      shipping: 2,
      receiving: 1,
      comment: 4
    },
    services: [
      { type: 'medical', icon: 'cross', text: '医疗保障', color: '#ee0a24', count: 1 },
      { type: 'points', icon: 'gift-o', text: '积分兑换', color: '#ff6b00', count: 520 },
      { type: 'welfare', icon: 'like', text: '我的优惠', color: '#ff2c7d', count: 2 },
      { type: 'service', icon: 'service-o', text: '客服中心', color: '#1989fa', count: 0 }
    ]
  },
  // 订单数据模拟
  orderData: {
    total: 10,
    list: [
      {
        id: 1,
        status: 'pending',
        products: [
          { name: '有机蔬菜', price: 68.00, quantity: 1 }
        ],
        total: 68.00,
        createTime: '2024-03-10 10:30:00'
      },
      {
        id: 2,
        status: 'shipping',
        products: [
          { name: '农用化肥', price: 299.00, quantity: 2 }
        ],
        total: 598.00,
        createTime: '2024-03-09 15:20:00'
      }
    ]
  }
}

export default {
  // 用户相关
  user: {
    // 注册
    register: (data) => {
      return api.post('/users/register', {
        username: data.username,
        password: data.password,
        phone: data.phone,
        is_admin: data.is_admin ? 1 : 0,
        village_id: data.village_id ? data.village_id : null
      })
    },

    // 登录
    login: async (data) => {
      const { username, password } = data;
      try {
        // 调用后端真实登录接口
        const response = await api.post('/users/login', { username, password });
        
        // 登录成功后存储 token 和用户信息到 localStorage
        if (response.code === 0) {
          localStorage.setItem('token', response.data.token);
          localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
        }

        return response; // 返回后端原始响应
      } catch (error) {
        // 响应拦截器已处理错误提示，此处直接抛出
        throw error;
      }
    },

    // 退出登录
    logout: () => {
      // 模拟退出登录成功
      return Promise.resolve({
        code: 0,
        message: '退出成功'
      })
    },

    // 获取用户信息
    getInfo: () => {
      // 从localStorage获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      return Promise.resolve({
        code: 0,
        data: userInfo
      })
    },

    getOrders: (params) => {
      // 模拟分页
      const { page = 1, pageSize = 10, status } = params
      let list = mockData.orderData.list
      if (status) {
        list = list.filter(order => order.status === status)
      }
      const start = (page - 1) * pageSize
      const end = start + pageSize
      return Promise.resolve({
        code: 0,
        data: {
          list: list.slice(start, end),
          total: list.length
        }
      })
    },

    getServices: () => Promise.resolve({ code: 0, data: mockData.userData.services })
  },
  
  // 天气相关
  weather: {
    get: () => Promise.resolve({ code: 0, data: mockData.weatherData })
  },

  // 视频相关
  video: {
    list: (params) => {
      // 模拟分页
      const { page, pageSize } = params
      const start = (page - 1) * pageSize
      const end = start + pageSize
      const data = mockData.videoList.slice(start, end)
      
      return Promise.resolve({
        code: 0,
        data,
        total: mockData.videoList.length
      })
    },
    detail: (id) => {
      const video = mockData.videoList.find(v => v.id === id)
      return Promise.resolve({ code: 0, data: video })
    }
  },

  // 商品相关
  product: {
    list: (params) => api.get('/product/list', { params }),
    detail: (id) => api.get(`/product/${id}`),
    addToCart: (data) => api.post('/cart/add', data),
    favorite: (id) => api.post(`/product/${id}/favorite`)
  },

  // 医疗服务相关
  medical: {
    services: () => api.get('/medical/services'),
    doctors: () => api.get('/medical/doctors'),
    makeAppointment: (data) => api.post('/medical/appointment', data)
  },

  // 体检相关
  health: {
    appointments: () => api.get('/health/appointments'),
    scheduleCheck: (data) => api.post('/health/schedule', data)
  },

  // 购物车相关
  cart: {
    list: () => api.get('/cart/list'),
    update: (data) => api.put('/cart/update', data),
    remove: (id) => api.delete(`/cart/${id}`)
  },

  // 收藏相关
  favorite: {
    list: () => api.get('/favorite/list'),
    add: (id) => api.post(`/favorite/add/${id}`),
    remove: (id) => api.delete(`/favorite/${id}`)
  }
} 